package com.chery.media.ui.play

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.chery.media.R
import com.chery.media.contacts.MusicType
import com.chery.media.databinding.ActivityMusicPlayerBinding
import com.chery.media.library.base.BaseVMActivity

class MusicPlayActivity: BaseVMActivity<MusicPlayViewModel, ActivityMusicPlayerBinding>() {

    private val musicTypeAdapter by lazy {
        MusicPlayTypeAdapter().apply {
            setOnItemClickListener { _, _, position ->
                val item = getItem(position)
//                playViewModel.setCurrentMusicType(item.type?:MusicType.BLUETOOTH)
                playViewModel.currentType.value = item.type
                setSelect(position)
                switchFragment(position)
            }
        }
    }

    private lateinit var showFragment: Fragment

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.musicType.adapter = musicTypeAdapter
        musicTypeAdapter.setList(viewModel.musicTypes)
        playViewModel.startService()
//        playViewModel.setCurrentMusicType(MusicType.BLUETOOTH)
        playViewModel.currentType.value = MusicType.BLUETOOTH
        showFragment = viewModel.musicFragments[0]
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.container, showFragment)
            .commitNow()
    }

    private fun switchFragment(index: Int) {
        val now = viewModel.musicFragments[index]
        supportFragmentManager.beginTransaction().apply {
            if (!now.isAdded) {
                add(R.id.container, now)
            }
            hide(showFragment)
            show(now)
            showFragment = now
            if (showFragment.isResumed) showFragment.onResume()
            commit()
        }
    }
}